<template>
    <div class="novel-detail">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator=">" class="breadcrumb-class">
            <el-breadcrumb-item style="padding: 10px 5px" :to="{ path: '/' }">36k小说网</el-breadcrumb-item>
            <el-breadcrumb-item
                style="padding: 10px 0"
                :to="{
                path: categoryRouteMap[novel.category] || '/'
              }">
                {{novel.category}}
            </el-breadcrumb-item>
            <el-breadcrumb-item style="padding: 10px 0">{{ novel.title}}</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 小说信息 -->
        <div class="novel-info">
            <div class="novel-cover">
                <el-image :src="novel.cover" style="width: 200px;height: 270px"  fit="cover"></el-image>
            </div>
            <div class="novel-meta">
                <h1>{{ novel.title }}</h1>
                <div class="meta-item">
                    <span>作者：{{ novel.author }}</span>
                    <span style="margin-left:110px ">类别：{{ novel.category }}</span>
                </div>
                <div class="meta-item">
                    <span>最后更新：{{ novel.lastUpdate }}</span>
                    <span>最新章节：{{ novel.latestChapter }}</span>
                </div>
                <div class="actions">
                    <el-button type="primary" plain @click="addBookmark()">加入书架</el-button>
                    <el-button type="primary" plain>投推荐票</el-button>
                    <el-button type="primary" plain>直达底部</el-button>
                    <el-button type="danger" plain>评论</el-button>
                </div>
                <!-- 小说简介 -->
                <div class="novel-intro">
                    <p>{{ novel.intro }}</p>
                    <p>本站提示：各位书友要是觉得《{{ novel.title }}》还不错的话请不要忘记向您QQ群和微博里的朋友推荐哦！</p>
                </div>
            </div>
        </div>
        <!-- 热门推荐 -->
        <div class="recommendations">
            <span>热门推荐：</span>
            <el-tag v-for="(item, index) in recommendations" :key="index" style="cursor: pointer;" effect="plain" >{{ item.title }}</el-tag>
        </div>

    </div>
    <div class="novel-detail">

        <div class="novel-detail-title">
            <div style="padding: 20px">《{{ novel.title }}》章节列表</div>
        </div>
<!--        -->
        <div class="content">
            <div class="row" v-for="(chapters, rowIndex) in chunkedChapters" :key="rowIndex">
                <div class="column" v-for="(chapter, colIndex) in chapters" :key="colIndex">
                    <div class="chapter-item">
                        <router-link :to="`/chapter/${bookId}/${chapter.id}`">{{ chapter.title }}</router-link>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref,onMounted,computed } from 'vue'
import request from '@/utils/request.js';
const categoryRouteMap = {
    '玄幻小说': '/XuanHuan',
    '网游小说': '/WangYou',
    '武侠小说': '/WuXia',
    '都市小说': '/DouShi',
    '科幻小说': '/KeHuang',
    '历史小说': '/LiShi',
    '言情小说': '/YanQin'

};

onMounted(() => {
    fetchNovelDetail();
    fetchNovelList();
});
const chapters = ref([]);
// 将章节分成三列
const chunkedChapters = computed(() => {
    const result = [];
    const columns = 3;
    for (let i = 0; i < chapters.value.length; i += columns) {
        result.push(chapters.value.slice(i, i + columns));
    }
    return result;
});
const fetchNovelList = () => {
    // 显示加载状态（可选，提升用户体验）
    // 使用 ElLoading.service 创建加载状态（修正的核心部分）
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    request.get('/api/books/list', {
        params: {
            bookId: props.bookId // 使用props传递的bookId
        }
    }).then(res => {
        if (res.code === 200 && res.data) {
            chapters.value = res.data; // 赋值正确的小说数据
        } else {
            ElMessage.error('获取小说列表失败：' + (res.message || '数据格式错误'));
        }
    }).catch(error => {
        ElMessage.error('网络错误：' + error.message);
    })
        .finally(() => {
        // 关闭加载状态
        loading.close();
    });
};
const addBookmark =  () => {
    try {
        const  response =  request.post(`/api/users/bookmarks`, {
            bookId: props.bookId,
            chapterId: 1,
            IsBookshelf:0,//判断是不是书架
            position: window.scrollY || 0, // 记录页面当前滚动位置
        }).then(response=>{
                if (response.code===200) {
                    ElMessage.success('已成功加入书架')
                }else {
                    ElMessage.error('添加书架失败: ' + response.message)
                }
            }
        )
    } catch (error) {
        console.error('加入书架失败:', error)
        ElMessage.error('添加书架失败，请重试')
    }
}
const novel = ref({
    title: '',
    cover: '',
    author: '',
    category: '',
    lastUpdate: '',
    latestChapter: '',
    intro: ''
})
const props = defineProps({
    bookId: {
        type: Number,
        required: true,
        default: null, // 允许初始 null
        validator: (value) => {
            // 允许初始 null，但有效值必须 ≥0
            return value === null || (typeof value === 'number' && value >= 0);
        }
    }
});
import { watch } from 'vue';
import {ElLoading} from "element-plus";
import router from "@/router/index.js";

watch(() => props.bookId, (newVal) => {
    if (newVal !== null) {
        console.log('有效 bookId:', newVal);
        // 执行数据加载逻辑
    }
}, { immediate: true });
console.log('子组件接收的bookId：', props.bookId);

//获取列表
const fetchNovelDetail = () => {
    // 显示加载状态（可选，提升用户体验）
    // 使用 ElLoading.service 创建加载状态（修正的核心部分）
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    request.get('/api/books/listdetail', {
        params: {
            bookId: props.bookId // 使用props传递的bookId
        }
    }).then(res => {
        if (res.code === 200 && res.data) {
            novel.value = res.data; // 赋值正确的小说数据
        } else {
            ElMessage.error('获取小说详情失败：' + (res.message || '数据格式错误'));
        }
    }).catch(error => {
        ElMessage.error('网络错误：' + error.message);
    }).finally(() => {
        // 关闭加载状态
        loading.close();
    });
};
const recommendations = ref([
        { title: "诸天影视从四合院开始", bookId: 1 },
        { title: "从小欢喜开启诸天之旅", bookId: 2 },
        { title: "火影：我在暗部苟成超影", bookId: 3 },
        { title: "狗尾续貂传", bookId: 4 },
        { title: "进化乐园，您就是天灾？", bookId: 826017 }
    ]
)

</script>

<style scoped>
.novel-detail {
    margin: 20px auto; /* 居中显示 */
    width: 1200px;
    border: 3px solid #6bb2fc; /* 蓝色边框 */
    /*padding: 5px; !* 内边距 *!*/
    border-radius: 4px; /* 可选：圆角边框 */
    background-color: #f6f6f6;
}
.breadcrumb-class{
    /*margin-bottom: 20px;*/
    font-size:0.8rem;

}
/* 面包屑导航 */
.el-breadcrumb {
    margin-bottom: 20px;
    background-color: #eefcfc;
    height: 50px;
}

/* 小说信息 */
.novel-info {
    display: flex;
    margin-bottom: 20px;
    margin-left: 40px;
}

.novel-cover {
    width: 200px;
    height: 270px;
    margin-right: 50px;
}

.novel-meta {
    flex: 1;
}

.novel-meta h1 {
    font-size: 1.5rem;
    margin-bottom: 10px;
}

.meta-item {
    margin-bottom: 10px;
}

.meta-item span {
    margin-right: 20px;
}

.actions {
    margin-top: 20px;
    margin-bottom: 20px;
}

.actions .el-button {
    margin-right: 10px;
}

/* 小说简介 */
.novel-intro {
    margin-bottom: 20px;
    line-height: 1.5;
}

/* 热门推荐 */
.recommendations {
    margin-left: 30px;
    margin-top: 20px;

    margin-bottom: 20px;
}

.recommendations .el-tag {
    margin-right: 10px;
}
.novel-detail-title{
/*    居中*/
    text-align: center;
    font-size: 1.6rem;
    margin-bottom: 20px;
    background-color: #c4c3c3;
}


/*列表*/
.content {
    display: flex;
    flex-direction: column;
}

.row {
    display: flex;
    margin-bottom: 10px;
}

.column {
    flex: 1;
    padding: 0 10px;
}

.chapter-item {
    padding: 5px 0;
    border-bottom: 1px dashed #dcdcdc;
}

.chapter-item a {
    text-decoration: none;
    color: #333;
}

.chapter-item a:hover {
    color: #007bff;
}
</style>